// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DefaultNameFactory.cs" company="">
//   
// </copyright>
// <summary>
//   Default name factory implementation
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Bbm.Persistence
{
	using System;
	using System.Text;

	/// <summary>
	/// Default name factory implementation (uses shortened names)
	/// </summary>
	class DefaultNameFactory : INameFactory
	{
		/// <summary>
		/// Calculates a name for the given object storage
		/// </summary>
		/// <param name="key">The key type. May be null.</param>
		/// <param name="value">The value value. Cannot be null.</param>
		/// <param name="domain">The domain. May be null.</param>
		/// <returns>
		/// A unique name which can be used for physical storage
		/// </returns>
		public virtual CacheStoreName GetNameForStore(Type key, Type value, string domain)
		{
			if (value == null) 
				throw new ArgumentNullException("value");

			return new CacheStoreName(Normalize(RecursiveName(key)), Normalize(RecursiveName(value)), Normalize(domain ?? ""));
		}

	    static string RecursiveName(Type type)
	    {
            if (type == null)
                return "";

	        var retval = type.Name;

            if (type.IsGenericType)
                foreach (var argument in type.GetGenericArguments())
                    retval += RecursiveName(argument);

	        return retval;
	    }

	    /// <summary>
		/// Returns a letters only version of the given name string
		/// </summary>
		/// <param name="name">
		/// The name value.
		/// </param>
		/// <returns>
		/// Normalized name
		/// </returns>
		static string Normalize(string name)
		{
			var retval = new StringBuilder();

			foreach (var ch in name)
				if (char.IsLetter(ch))
					retval.Append(ch);

			return retval.ToString();
		}
	}
}